package cn.kgc.tangcco.controller;

import cn.kgc.tangcco.model.ResponseText;
import cn.kgc.tangcco.model.ResultCode;
import cn.kgc.tangcco.pojo.Account;
import cn.kgc.tangcco.utils.token.BaseJwtUtil;
import cn.kgc.tangcco.vo.Login;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/12/29 19:24
 */
@RestController
@RequestMapping(value = "/account")
public class AccountController {
    @Value("${jwt.key}")
    private String key;

    @Value("${jwt.expiryDate}")
    private Long expiryDate;

    @PostMapping(value = "/login")
    public ResponseText<Map<String, String>> login(Login login) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isBlank(login.getMobile()) || StringUtils.isBlank(login.getCode())) {
            return new ResponseText<>(ResultCode.PARAM_ERROR.getCode(), ResultCode.PARAM_ERROR.getMsg(), new HashMap<>());
        }
        Account account = new Account(login.getMobile(), "李昊哲", 95L);
        map.put("account", JSON.toJSONString(account));
        String token = BaseJwtUtil.jwtEncode(key, map, expiryDate);
        // 存储鉴权token
        map.put("Authentication", token);
        return new ResponseText<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), map);
    }

    @GetMapping(value = "/query")
    public ResponseText<Account> query(@RequestHeader(value = "Authentication", required = false) String token) {
        System.out.println(token);
        if (StringUtils.isBlank(token)) {
            return new ResponseText<>(ResultCode.NO_LOGIN.getCode(), ResultCode.NO_LOGIN.getMsg(), null);
        }
        DecodedJWT decodedJWT = BaseJwtUtil.jwtDecode(token, key);
        if (decodedJWT == null) {
            return new ResponseText<>(ResultCode.NO_LOGIN.getCode(), ResultCode.NO_LOGIN.getMsg(), null);
        }
        String text = decodedJWT.getClaim("account").asString();
        return new ResponseText<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), JSONObject.parseObject(text,Account.class));
    }
}
